package com.hm.oltu.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.querydsl.QPageRequest;
import org.springframework.stereotype.Service;

import com.hm.oltu.auto.PasswordHelper;
import com.hm.oltu.model.User;
import com.hm.oltu.repository.UserRepository;
import com.hm.oltu.service.UserService;
import com.hm.oltu.su.PageInfo;
import com.hm.oltu.vo.UserVo;

@Service
public class UserServiceImpl implements UserService {

	@Autowired
	private UserRepository userRepository;

	@Autowired
	private PasswordHelper passwordHelper;

	@Override
	public User createUser(UserVo userVo) {
		User user = new User();
		{
			user.setUsername(userVo.getUsername());
			user.setPassword(userVo.getPassword());
			user.setSalt(userVo.getSalt());
			user.setCreateTime(new Date().getTime());
			user.setExtension(userVo.getExtension());
		}
		// 加密密码
		passwordHelper.encryptPassword(user);
		return userRepository.save(user);
	}

	@Override
	public User updateUser(UserVo userVo) {
		User user = userRepository.findOne(userVo.getId());
		{
			user.setUsername(userVo.getUsername());
			user.setPassword(userVo.getPassword());
			user.setSalt(userVo.getSalt());
		}
		return userRepository.save(user);
	}

	@Override
	public void deleteUser(String userId) {
		userRepository.delete(userId);
	}

	@Override
	public void changePassword(String userId, String newPassword) {
		User user = userRepository.findOne(userId);
		user.setPassword(newPassword);
		passwordHelper.encryptPassword(user);
		userRepository.save(user);
	}

	@Override
	public User findOne(String userId) {
		return userRepository.findOne(userId);
	}

	@Override
	public User findByUsername(String username) {
		return userRepository.findByUsername(username);
	}

	@Override
	public boolean checkUser(String username, String password, String salt, String encryptpwd) {
		String pwd = passwordHelper.encryptPassword(username, password, salt);
		return pwd.equals(encryptpwd);
	}

	@SuppressWarnings("unchecked")
	@Override
	public PageInfo<UserVo> query(int pageNo, int pageSize) {
		PageInfo<UserVo> pageInfo = new PageInfo<UserVo>(pageNo, pageSize);

		Pageable pageable = new QPageRequest(pageInfo.getPageNumber(), pageInfo.getPageSize());

		List<UserVo> vos = new ArrayList<UserVo>();
		@SuppressWarnings("rawtypes")
		Page page = userRepository.findAll(pageable);
		page.getContent().forEach(userModel -> {
			UserVo userVo = new UserVo();
			BeanUtils.copyProperties(userModel, userVo);
			userVo.setCreateTime(((User) userModel).getCreateTime());
			vos.add(userVo);
		});

		return pageInfo.execute(page, vos);
	}

}
